import React, { PureComponent } from "react";
import { connect } from "dva";
import style from "styled-components";
import { Input, Button, message, DatePicker, Checkbox, Modal, Form, TreeSelect } from 'antd';
import Drawer from 'react-motion-drawer';
import PTable from "../../../components/Pro/PTable";
import EditIncentive from "./EditIncentive";
import { addComSecurityAward, deleteComSecurityAwardById, getTreeperBydepart } from "../../../services/api";
import PSelect from "../../../components/Pro/PSelect";
import PZhezhao from "../../../components/Pro/PZhezhao";


const FormItem = Form.Item;
const dateFormat = 'YYYY/MM/DD';
const { confirm } = Modal;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const config = {
  rules: [
    {
      type: 'object',
      required: false,
      message: '请选择日期!'
    }
  ]
};


@connect(state => ({ profile: state.profile }))
@Form.create()

export default class Incentive extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      visible: false,
      open: false, //新增
      openEdit: false, //修改
      awardId: 0, //id
      forceUpdate: false,
      showPerId: 0,
      valueTree: [],
      treeData: [//树
        {
          title: "",
          key: ""
        }
      ],
      pageParm: {
        pageSize: "10",
        pageNumber: "1",
        keyWords: "",
        startDate: "",
        endDate: "",
      },
      keyWords: "",
      startDate: "",
      endDate: "",
    };
  }

  componentDidMount() {
    getTreeperBydepart({}).then(response => {
      console.log(response, "getTreeperBydepart-response");
      this.setState({ treeData: response.data });
    }, err => {
      console.log(err, "getTreeperBydepart-err");
    });
  }
  //时间选择
  onChangeTime = (date, dateString) => {
    this.setState({ startDate: dateString[0], endDate: dateString[1] });
  };

  //修改
  editDrawer = (awardId) => {
    this.setState({ awardId });
    this.setState({ openEdit: true });
  };

  //增加
  addDrawer = () => {
    this.setState({ open: true });
  };
  //输入框的书写
  inputSerchIncentiveChange = (e) => {
    console.log(e.target.value.trim());
    this.setState({
      keyWords: e
        .target
        .value
        .trim()
    });
  };
  //报表类型 change
  pSelectChange = (value, type) => {
    this.setState({ [type]: value });
  };

  hideModal = () => {
    this.setState({
      visible: true,
    });
  };

  handleModalOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
      open: false,
    });
  };

  handleModalCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };

  //刷新方法
  tableUpdate = () => {
    this.setState({
      forceUpdate: true
    }, () => {
      this.setState({ forceUpdate: false });
    });
  };

  //点击搜索
  search = () => {
    const pageParm = {
      ...this.state.pageParm
    };
    const { keyWords, startDate, endDate } = this.state;
    pageParm.keyWords = keyWords;
    pageParm.startDate = startDate;
    pageParm.endDate = endDate;
    this.setState({ pageParm });
  };
  //渲染表格
  renderTable = () => {
    const columns = [
      {
        title: '奖励日期',
        dataIndex: 'awardDate',
        key: 'awardDate',
        width: 130
      }, {
        title: '奖励单位',
        dataIndex: 'awardUnit',
        key: 'awardUnit',
        width: 130
      }, {
        title: '表彰奖励内容',
        dataIndex: 'awardContent',
        key: 'awardContent',
        width: 330,
        render: (text, record) => (
          <div>
            <p style={{ width: 350, whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden', marginTop: '8px', marginBottom: '8px' }}>{record.awardContent}</p>
          </div>
        )
      }, {
        title: '表彰奖励原因',
        dataIndex: 'awardReason',
        key: 'awardReason',
        width: 330,
        render: (text, record) => (
          <div>
            <p style={{ width: 350, whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden', marginTop: '8px', marginBottom: '8px' }}>{record.awardReason}</p>
          </div>
        )
      }, {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        width: 110,
        render: (text, record) => (
          <div>
            <Opton onClick={this.editDrawer.bind(this, record.awardId)} style={{ color: '#0F71FF', fontSize: '14px' }}>修改</Opton>
            <Opton onClick={this.showDeleteConfirm.bind(this, record.awardId)} style={{ color: '#0F71FF', fontSize: '14px' }}>删除</Opton>
          </div>
        ),
      }
    ];
    return (<PTable
      style={{
        marginTop: 20
      }}
      columns={columns}
      url="listComSecurityAward"
      pageParm={this.state.pageParm}
      forceUpdate={this.state.forceUpdate} />);
  };

  showDeleteConfirm = (awardId) => {
    console.log(awardId);
    const that = this;
    confirm({
      title: '是否删除所选信息，删除后无法找回。是否确认删除？',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        console.log("ok");
        that.orderDelete(awardId);
      },
      onCancel() {
        console.log('Cancel');
      },
    });

  };

  //删除
  orderDelete = (awardId) => {
    deleteComSecurityAwardById({ awardId }).then(() => {
      this.tableUpdate();
    }, (err) => {
      console.log(err);
    });
  };
  //树形选择器改编
  handleTreeSelectChange = (value, label, extra) => {
    this.setState({ showPerId: 0 });
    const lastValue = this.state.valueTree;
    if (extra.triggerNode && extra.triggerNode.props && extra.triggerNode.props.treeType === "1") {
      console.log("部门");
      this.setState({ valueTree: lastValue });
    } else {
      this.setState({ valueTree: value });
    }
  };


  //表单提交
  handleIncentiveSubmit = (e) => {
    e.preventDefault();
    this
      .props
      .form
      .validateFields((err, values) => {
        console.log("表单提交......", values);
        values.perIdString = this.state.valueTree;
        console.log(values.remark, "备注.。");
        console.log(values.perIdString, "人员");
        values.perIdString.length === 0 && this.setState({ showPerId: 1 });

        if (!err && values.perIdString) {
          const rangeValue = values["awardDate"];
          values.awardDate = rangeValue.format("YYYY-MM-DD");
          const { isPoliceAward } = values;
          if (isPoliceAward) {
            values.isPoliceAward = "1";
          } else {
            values.isPoliceAward = "0";
          }

          addComSecurityAward(values).then(data => {
            console.log(data);
            this.setState({ forceUpdate: true });
            this.setState({ open: false });
            this.setState({ valueTree: [] });
            this.tableUpdate();
            const { setFieldsValue } = this.props.form;
            console.log(this.props.form);
            setFieldsValue({
              awardDate: "",
              awardType: "",
              awardUnit: "",
              isPoliceAward: false,
              awardContent: "",
              awardReason: "",
              remark: ""
            });
          }, err1 => {
            console.log(err1);
          });
        }
      });
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 7
        }
      },
      wrapperCol: {
        xs: {
          span: 24
        },
        sm: {
          span: 17
        },
        md: {
          span: 17
        }
      }
    };
    const { getFieldDecorator } = this.props.form;
    return (

      <Content>
        {/* 搜索条件面板 */}
        <div className="searchpanel">
          <Form className="Wrapper-form" layout="inline" onSubmit={this.handleSubmit}>
            <FormItem
              {...formItemLayout}
              label="关键字："
              colon={false}
              style={{
                marginTop: 0
              }}>
              <Input
                style={{
                  width: 214
                }}
                maxLength="20"
                onChange={this.inputSerchIncentiveChange}
                placeholder="搜索奖励内容、原因、单位" />
            </FormItem>
            <FormItem {...formItemLayout} label="奖励日期:" colon={false} className="post">
              <RangePicker
                style={{
                  width: 214
                }}
                showTime={{
                  format: "HH:mm"
                }}
                format={dateFormat}
                onChange={this.onChangeTime} />
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=""
              colon={false}
              style={{
                marginTop: 0
              }}>
              <Button
                type="primary"
                style={{
                  marginLeft: 17
                }}
                onClick={this.search}>
                搜索
              </Button>
            </FormItem>
            <br />
            <FormItem {...formItemLayout} label="" colon={false}>
              <div className="btns">
                <Button type="primary" onClick={this.addDrawer}>新增奖励</Button>
              </div>
            </FormItem>
          </Form>
        </div>
        {this.renderTable()}
        <Modal
          title="删除的奖励信息不可恢复"
          visible={this.state.visible}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}>
          <p>确认删除“奖励信息”？</p>
        </Modal>


        {/*奖励详情*/}
        <Drawer
          overlayColor="rgba(0, 0, 0,0)"
          right
          open={this.state.open}
          noTouchClose
          width={600}
          zIndex={2}
          className="drawer-box"
          onChange={(open) => {
            this.setState({ open });
          }}>
          <div className="drawer">
            <div className="drawer-header">奖励详情</div>
            <div className="drawer-content">
              <Form
                style={{
                  marginTop: 24
                }}
                onSubmit={this.handleIncentiveSubmit}>

                  {this.state.showPerId === 1 ?
                    <Formitem style={{ marginLeft: 50,marginBottom:0, 'display': 'inline-block' }}>
                    <Formlable >
                      <span style={{ color: '#f5222d' }}>* </span>被表彰奖励人员:</Formlable>
                    <TreeSelect
                      value={this.state.valueTree}
                      style={{
                        width: 294,
                        border: '1px solid #f5222d',
                        borderRadius: 4
                      }}
                      dropdownStyle={{
                        maxHeight: 400,
                        overflow: "auto"
                      }}
                      treeData={this.state.treeData}
                      onChange={this.handleTreeSelectChange}
                      treeDefaultExpandAll
                      multiple
                    />
                      <div style={{ 'color': '#f5222d', marginLeft: 114 }}> 请选择奖励人员</div>
                    </Formitem>
                    :
                    <Formitem style={{ marginLeft: 50,marginBottom:24, 'display': 'inline-block' }}>
                    <Formlable >
                      <span style={{ color: '#f5222d' }}>* </span>&nbsp;被表彰奖励人员:</Formlable>
                    <TreeSelect
                      value={this.state.valueTree}
                      style={{
                        width: 294,
                      }}
                      dropdownStyle={{
                        maxHeight: 400,
                        overflow: "auto"
                      }}
                      treeData={this.state.treeData}
                      onChange={this.handleTreeSelectChange}
                      treeDefaultExpandAll
                      multiple
                    />
                    <div/>
                    </Formitem>
                 }

                <FormItem {...formItemLayout} label="表彰日期">
                  {getFieldDecorator("awardDate", {
                    rules: [
                      {
                        required: true,
                        message: "请选择表彰日期"
                      }
                    ]
                  }, config)(<DatePicker style={{ width: 294 }} />)}
                </FormItem>
                <FormItem {...formItemLayout} label="表彰类型">
                  {getFieldDecorator('awardType', {
                    rules: [
                      {
                        required: true, message: '请选择表彰类型'
                      }
                    ]
                  })(<PSelect
                    type="awardType"
                    style={{
                      width: 294
                    }}
                     />)}
                </FormItem>
                <FormItem {...formItemLayout} label="做出表彰奖励单位">
                  {getFieldDecorator('awardUnit', {
                    rules: [
                      {
                        required: true, message: '请填写做出表彰奖励单位'
                      }
                    ]
                  })(<Input
                    style={{
                      width: 294
                    }}
                    maxLength="50"
                    placeholder="请输入" />)}
                </FormItem>

                <FormItem {...formItemLayout} label="公安机关给予表彰奖励">
                  <div style={{
                    width: 294
                  }}>
                    {getFieldDecorator('isPoliceAward', {
                      valuePropName: 'checked',
                      initialValue: false,
                      rules: [
                        {
                          required: false, message: '请填写公安机关是否给予表彰奖励'
                        }
                      ]
                    })(<Checkbox style={{
                      width: 294
                    }} />)}
                  </div>
                </FormItem>
                <FormItem {...formItemLayout} label="表彰奖励内容">
                  {getFieldDecorator('awardContent', {
                    rules: [
                      {
                        required: true, message: '请填写表彰奖励内容'
                      }
                    ]
                  })(<TextArea
                    style={{
                      width: 294
                    }}
                    maxLength="500"
                    rows={4}
                    placeholder="请输入" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="表彰奖励原因">
                  {getFieldDecorator('awardReason', {
                    rules: [
                      {
                        required: true, message: '请填写表彰奖励原因'
                      }
                    ]
                  })(<TextArea
                    style={{
                      width: 294
                    }}
                    maxLength="500"
                    rows={4}
                    placeholder="请输入" />)}
                </FormItem>
                <FormItem {...formItemLayout} label="备注">
                  {getFieldDecorator("remark", { initialValue: "" })(<TextArea
                    style={{
                      width: 294
                    }}
                    maxLength="500"
                    rows={4}
                    placeholder="请输入" />)}
                </FormItem>
              </Form>
            </div>
            <div className="drawer-footer">
              <Button onClick={this.hideModal}>返回</Button>
              <Button type="primary" onClick={this.handleIncentiveSubmit}>提交</Button>
            </div>
          </div>
        </Drawer>
        <Modal
          title="提示"
          visible={this.state.visible}
          onOk={this.handleModalOk}
          onCancel={this.handleModalCancel}>
          <p>当前信息未保存，是否确认返回？</p>
        </Modal>
        {/* {(this.state.open || this.state.openEdit) && (
          <PZhezhao top={"2px"}/>
        )} */}
        <EditIncentive
          onChange={openEdit => {
            this.setState({ openEdit });
          }}
          visible={this.state.openEdit}
          awardId={this.state.awardId}
          tableUpdate={this.tableUpdate} />
      </Content>
      
    );
  }
}

/************************样式************************/

const Content = style.div`{
  font-size: 14px;
  color: rgba(0,0,0,0.65);
  .searchpanel{
     margin-bottom:16px;
    .post{
      margin:0 8px 0 16px;
    }
  }
  .btns{
    margin-top:16px;
  }
}`;

const Opton = style.span`{
  font-size: 12px;
  color: #0F71FF;
  cursor:pointer;
  margin-right:8px;
}`;

const Formitem = style.label`{

  font-family: "Monospaced Number", "Chinese Quote", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 14px;
  line-height: 1.5;
  color: rgba(0, 0, 0, 0.65);
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  list-style: none;
  vertical-align: top;
  -webkit-transition: margin 0.15s steps(1);
  transition: margin 0.15s steps(1);
}`;
const Formlable = style.span`{
  text-align: right;
  vertical-align: middle;
  line-height: 39.9999px;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  margin-right:8px;
}`;

